<!--
* description: 备件奖励金操作
* author: xiaochengzuan
* createdDate: 2021-1-25
-->
<template>
  <section class="editBigAreaInfo">
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      :title="textMap[popupsState]"
      :append-to-body="true"
      :visible.sync="curPopupsVisible"
      width="70%"
      @close="closeEdit"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :style-type="$store.state.app.dialogType"
      />

      <div class="filter-container filter-params">
        <el-row ref="vailComponentList" :gutter="26">
          <component
            :is="comp.component"
            v-for="comp in tableComponents.filter(o => o.isMust === true)"
            :ref="comp.isRequire ? comp.isRequire+ comp.compKey : comp.compKey"
            :key="comp.compKey"
            :code-field="comp.codeField"
            :text-field="comp.textField"
            :popups-key="comp.compKey"
            :is-show="comp.isShow"
            :code="formField[comp.codeField]"
            :text="formField[comp.textField]"
            :init-first="comp.initFirst"
            :disabled="comp.disabled"
            :is-mul="comp.isMul"
            :is-require="comp.isRequire"
            :span="comp.span || 6"
            :label-name="comp.labelName"
            :custom-obj="comp.customObj"
            :lookuptype="comp.lookuptype"
            :input-type="comp.inputType"
            :date-options-type="comp.dateOptionsType"
            :format="comp.format"
            :start-time="comp.startTime"
            :date-type="comp.dateType"
            :clearable="comp.clearable"
            :filterable="comp.filterable"
            :parent-fileds="comp.parentFileds || ''"
            :must-fields="comp.mustFields || ''"
            :return-code-field="comp.returnCodeField"
            :return-text-field="comp.returnTextField"
            :other-field="comp.otherField"
            :is-async="comp.isAsync"
            :validrule="comp.validrule"
            :is-use-default="comp.isUseDefault"
            :is-host="comp.isHost"
            :o-fields="comp.oFields"
            :category="comp.category"
            :un-list-qury-fields="comp.unListQuryFields"
            :data-to-object="comp.dataToObject"
            :options="comp.options"
            :step="comp.step"
            :init-stop-select="comp.initStopSelect"
            :is-input="comp.isInput"
            @changeCode="getComponentCode"
            @focusCode="getFocusCode"
          />
        </el-row>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button
          v-for="comp in tableButtons"
          :key="comp.compKey"
          :type="comp.type"
          :icon="comp.icon"
          @click="comp.clickEvent"
        >{{ comp.text }}</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import { formMixins } from '@/components/mixins/formMixins'
import api from './api'
export default {
  components: {
    dialogHeader: () => import('@/components/dialogHeader'),
    mixButton: () => import('@/components/basicComponent/mixButton')

  },

  // 组件混入对象
  mixins: [formMixins],

  props: {
    popupsVisible: { type: Boolean, default: false },
    // 从网格传入的编辑行数据(json)
    dynamicEditRowData: { type: Object, default: function() { return {} } }
  },

  data() {
    const viewPageCode = 'bigAreaInfo-edit'
    return {
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          icon: 'iconfont  icon-preservation',
          clickEvent: () => this.save(),
          text: this.$t('sys.button.save') /* 保存*/,
          position: 'right'
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          icon: 'iconfont  icon-cancel',
          clickEvent: () => this.close(),
          text: this.$t('sys.button.cancel') // 取消
        }
      ],

      // 动态组件-查询条件
      tableComponents:
          [
            {
              compKey: 'compKey1',
              labelName: '操作单号：',
              codeField: 'dlrDiscountOrderCode',
              component: () => import('@/components/org/commonInput'),
              isRequire: true,
              isInput: true,
              isMust: true,
              disabled: true,
              span: 8
            },
            {
              compKey: 'comKey2',
              labelName: '网点编码：',
              codeField: 'dlrCode',
              textField: 'dlrShortName',
              otherField: 'dlrId',
              component: () => import('@/views/ve/planReport/components/multipleSearchInput'),
              isMust: true,
              // disabled: true,
              customObj: { showType: '' },
              dataToObject: {
                oFields: 'dlrCode,dlrShortName',
                // 控制弹窗页面 搜索 网格 元素
                tableComponents: [
                  {
                    compKey: 'compKey1',
                    labelName: '网点名称：',
                    codeField: 'dlrShortName',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  },
                  {
                    compKey: 'compKey2',
                    labelName: '网点编码：',
                    codeField: 'dlrCode',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  }
                ],
                tableCols: [
                  {
                    prop: 'dlrCode',
                    label: '网点编码'
                  },
                  {
                    prop: 'dlrShortName',
                    label: '网点名称'
                  }
                ],
                formField: {
                  dlrShortName: '',
                  dlrCode: ''
                },
                returnField: {
                  prop: 'dlrCode',
                  label: '网点编码'
                },
                api: api.queryOrgDlrCodes
              },
              span: 8,
              isRequire: true
            },
            {
              compKey: 'compKey3',
              labelName: '操作类型：',
              codeField: 'actionType',
              textField: 'actionTypeCn',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'actionType,actionTypeCn',
              options: [
                { actionType: '1', actionTypeCn: '上账' },
                { actionType: '0', actionTypeCn: '冻结' }
              ],
              type: 'dropdownList',
              isMul: false,
              isMust: true,
              isRequire: true,
              span: 8
            },
            {
              compKey: 'compKey5',
              labelName: '操作金额：',
              codeField: 'account',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              isInput: true,
              isRequire: true,
              span: 8,
              validrule: {
                // 保留一到两位小数
                isformat: /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/,
                resectMessage: {
                  isformat: '请输入正确的价格，价格最多保留两位小数!'
                }
              }
            },
            {
              compKey: 'compKey6',
              labelName: '红色通知单号：',
              codeField: 'redNoticeNumber',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isInput: true,
              isMust: true,
              isRequire: true,
              span: 8
            },
            {
              compKey: 'compKey7',
              labelName: '备注：',
              codeField: 'remark',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isInput: true,
              isMust: true,
              span: 8
            }
          ],

      // 标题
      textMap: {
        edit: '备件奖励单编辑',
        add: '备件奖励单新增'
      },

      // 表单数据（无需赋值，由混入对象赋值）
      formField: {}
    }
  },
  created() {
    this.genFormField()
    this.execCreated()
    this.setDisable()
  },
  mounted() {
    // 获取网点信息
    const { DLR_ID, DLR_CODE, DLR_NAME } = this.$store.state.user.orgInfo
    if (this.popupsState === 'add') {
      this.formField.dlrId = DLR_ID
      this.formField.dlrCode = DLR_CODE
      this.formField.dlrShortName = DLR_NAME
    }
    // 新增 生成操作单号
    if (this.popupsState === 'add') {
      debugger
      this.getControlOrderCode()
    }
  },
  methods: {
    getControlOrderCode() {
      this.$requestAPI({
        apiUrl: 'mp/e3sh/spareparts/finance/bonusOrderMakeService/queryBounsOrderCode.do',
        variables: {}
      }).then(res => {
        if (res.result === '1') {
          console.log(this)
          this.formField.dlrDiscountOrderCode = res.rows[0].bonusOrderCode
        } else {
          this.$message(res.msg ? res.msg : '')
        }
      }).catch(err => {
        if (err.response.data.msg) {
          this.$message(err.response.data.msg)
        } else {
          this.$message(err.message)
        }
      })
    },
    genFormField() {
      const viewPageCode = this.$route.path
      this.genCodeFiled = this.genUtil(this.tableComponents)
      const formField = this.genCodeFiled()
      this.formField = this.$utils.getFormField(this, formField, this.$ConfigCache.CacheConfig.cacheData[viewPageCode])
    },
    // 生成formField
    genUtil: (array) => (attr1 = 'codeField', attr2 = 'textField', attr3 = 'otherField') => array.reduce((p, c) => {
      p[c[attr1]] = ''
      // eslint-disable-next-line no-prototype-builtins
      c.hasOwnProperty(attr2) ? p[c[attr2]] = '' : ''
      c.hasOwnProperty(attr3) ? p[c[attr3]] = '' : ''
      return p
    }, {}),
    closeEdit() {
      this.$emit('update:curPopupsVisible', false)
    },
    // 新增/编辑保存按钮
    save() {
      const that = this
      this.$utils.validataMoth(this, 'validpopup')
      if (this.valid) {
        if (that.popupsState === 'edit') {
          that.editSave()
        } else {
          that.addSave()
        }
      }
    },
    // 覆盖混入中的 setOtherField方法
    setOtherField(comType, otherField, selectData) {
      if (selectData) {
        this.formField[otherField] = selectData[otherField]
      }
    },
    // 编辑保存
    editSave() {
      const { updateControlId, dlrDiscountOrderId } = this.dynamicEditRowData
      this.$requestAPI({
        apiUrl: api.editBonusOrderOperate.APIUrl,
        variables: { ...this.formField, updateControlId, dlrDiscountOrderId }
      }).then(response => {
        if (response.result === '1') {
          this.$message('修改成功')
          this.curPopupsVisible = false
          this.$nextTick(() => {
            this.$parent.queryTable(1)
          })
        } else {
          // 保存失败
          this.$message({ message: '保存失败:' + response.msg })
        }
        this.curPopupsVisible = false
      })
    },

    // 新增保存
    addSave() {
      const that = this
      const queryObj = {
        type: 'mutation',
        apiConfig: api.addBonusOrderOperate,
        variables: that.formField
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.$message({
            message: '添加成功',
            type: 'success',
            duration: 1000
          })
          this.curPopupsVisible = false
          this.$nextTick(() => {
            this.$parent.queryTable(1)
          })
        } else {
          // 保存失败
          this.$message({
            message:
              '添加失败:' + response.msg,
            type: 'warn',
            duration: 1000
          })
        }
        this.curPopupsVisible = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.promptSpan{
  position: absolute;
  bottom: 26px;
  right: 335px;
  color: #e70020;
}
</style>

